package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.CheckItemDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.CheckItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.net.InterfaceAddress;
import java.util.List;

/**
 * @author zhouwei
 * @date 2019-12-29 19:55
 */
@Service(interfaceClass=CheckItemService.class)
@Transactional
public class CheckItemServiceImpl implements CheckItemService {
    //调用dao
    @Autowired
    private CheckItemDao checkItemDao;

    //添加检查项
    @Override
    public void add(CheckItem checkItem) throws RuntimeException{
        //校验项目名，项目编码的唯一性
        List<Integer> codeid = checkItemDao.checkItemByCode(checkItem);
        List<Integer> nameid = checkItemDao.checkItemByName(checkItem);
        if(codeid.size()==0&&nameid.size()==0) {
            checkItemDao.add(checkItem);
        }else{
            throw new RuntimeException("项目名或项目编码已存在，请重新输入！");
        }
    }


    //分页
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage=queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        //使用mybaties的分页助手
        PageHelper.startPage(currentPage,pageSize);
        //调用dao,获得page，page对象已将tatal，result封装好了
        Page<CheckItem> page = checkItemDao.findByCondition(queryPageBean);
        long total = page.getTotal();
        List<CheckItem> rows = page.getResult();
        return  new PageResult(total,rows);
    }


    //删除检查项
    @Override
    public void delete(Integer id) throws RuntimeException {
        //是否存在关联表，
        int count=checkItemDao.checkItemgroupByid(id);
        if(count>0){
            throw new RuntimeException("当前检查项被引用，无法删除");
        }
        checkItemDao.delete(id);
    }


    //查找单个检查项
    @Override
    public Result findById(Integer id) {
        CheckItem checkItem=new CheckItem();
        try {
            checkItem=checkItemDao.findById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_CHECKITEM_FAIL,checkItem);
        }
        return new Result(true,MessageConstant.QUERY_CHECKITEM_SUCCESS,checkItem);
    }

    //编辑检查项
    @Override
    public void edit(CheckItem checkItem) {
        checkItemDao.edit(checkItem);
    }

    //所有检查项
    @Override
    public List<CheckItem> findAll() {
        return checkItemDao.findAll();
    }
}
